package com.zhangkunhao.month05.day21.sort;

/**
 * 改进的数组（无序）顺序查找指定值是否存在算
 */
public class SequentialSearchPro {

    // 改进的顺序搜索算法
    public static int sequentialSearch(int[] A, int K) {
        // 将K添加到数组末尾
        int originalLength = A.length;
        int[] extendedArray = new int[A.length + 1];
        System.arraycopy(A, 0, extendedArray, 0, originalLength);
        extendedArray[originalLength] = K;

        // 开始搜索
        int i = 0;
        //把查找键添加到列表的末尾，那么查找一定成功，所以不必每次循环都检查是否到了表的末尾。
        while (extendedArray[i] != K) {
            i++;
        }

        // 检查是否找到元素K
        return i < originalLength ? i : -1;
    }

    public static void main(String[] args) {
        int[] array = {1, 3, 5, 7, 9};
        int key = 5;

        int resultIndex = sequentialSearch(array, key);
        if (resultIndex != -1) {
            System.out.println("Element found at index: " + resultIndex);
        } else {
            System.out.println("Element not found.");
        }
    }
}
